<template>
  <header>
    <i class="iconfont icon-fanhui" @click="$router.back()"></i>

    <div class="search-input">
      <i class="iconfont icon-fangdajing"></i>
      <input
        type="text"
        placeholder="搜索你喜欢的产品..."
        @keyup.enter="handleSearch"
        v-model="searchVal"
      >
    </div>
    <span @click="handleSearch">搜索</span>
    
  </header>
</template>

<script setup>
import { ref } from "vue"
import { useRoute, useRouter } from "vue-router"

const route = useRoute()
const router = useRouter()

const searchVal = ref(route.query.searchName) || ref('')

const handleSearch = () => {
  //如果搜索框值为空 或者 跟上次搜索一样就不进行页面跳转
  if (!searchVal.value || searchVal.value === route.query.searchName) return

  //获取本地存储localStorage 并把当前搜索框值保存进去
  if ( !localStorage.getItem('localHistorySearch') ) {
    localStorage.setItem('localHistorySearch', '[]')
  }
  const localHistorySearch = JSON.parse( localStorage.getItem('localHistorySearch') )
  localHistorySearch.unshift(searchVal.value)
  
  //同es6 set去重后 重新保存到localStorage
  let arr = new Set(localHistorySearch)
  localStorage.setItem('localHistorySearch', JSON.stringify( Array.from(arr) ))

  router.push({
    path: '/search/list',
    query: {
      searchName: searchVal.value
    }
  })
}
</script>

<style lang="less" scoped>
header {
  display: flex;
  align-items: center;
  height: 45px;
  background-color: #b0352f;
  color: #fff;

  .icon-fanhui {
    font-size: 28px;
    width: 45px;
    line-height: 45px;
    text-align: center;
  }

  .search-input {
    flex: 1;
    position: relative;

    .iconfont {
      position: absolute;
      top: 50%;
      transform: translateY(-50%);
      left: 8px;
      color: rgb(175, 175, 175);
      font-size: 18px;
    }

    input {
      outline: none;
      width: 100%;
      height: 30px;
      border-radius: 30px;
      border: none;
      padding: 5px 5px 5px 30px;
      box-sizing: border-box;
      background-color: #fff;
      color: #000;
      font-size: 14px;
    }
  }

  span {
    font-size: 16px;
    width: 45px;
    line-height: 45px;
    text-align: center;
  }
}
</style>